package com.mdlib.helper.ui.fragments.sect.my;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.ljlib.core.util.common.StringUtils;
import com.ljlib.core.util.common.TimeUtils;
import com.ljlib.help.R;
import com.mdlib.helper.api.DataManager;
import com.mdlib.helper.api.network.RxHelper;
import com.mdlib.helper.api.network.RxSubscribe;
import com.mdlib.helper.base.BaseTitleFragment;
import com.mdlib.helper.common.CommonAdapter;
import com.mdlib.helper.common.CommonViewHolder;
import com.mdlib.helper.event.AddServiceEvent;
import com.mdlib.helper.event.EavluationEvent;
import com.mdlib.helper.model.AccountModel;
import com.mdlib.helper.model.BaseResult;
import com.mdlib.helper.model.entity.OrderDetailsInfo;
import com.mdlib.helper.model.entity.OrderEntity;
import com.mdlib.helper.model.entity.ServiceMoney;
import com.mdlib.helper.ui.UIHelper;
import com.mdlib.helper.ui.adapter.OrderDetailsAdapter;
import com.mdlib.helper.ui.fragments.sect.money.OrderExceptionFragment;
import com.mdlib.helper.ui.fragments.sect.money.OrderPayFragment;
import com.mdlib.helper.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 作者：HQY on 16/11/23 11:05
 * 邮箱：hqy_xz@126.com
 */

public class SendOrdersDetailsFragment extends BaseTitleFragment {


    @Bind(R.id.tv_details_type)
    TextView mTvDetailsType;
    @Bind(R.id.tv_details_goods_name)
    TextView mTvDetailsGoodsName;
    @Bind(R.id.rv_details_pic)
    GridView mRvDetailsPic;
    @Bind(R.id.tv_details_time)
    TextView mTvDetailsTime;
    @Bind(R.id.tv_details_address)
    TextView mTvDetailsAddress;
    @Bind(R.id.tv_details_addresses)
    TextView mTvDetailsAddresses;
    @Bind(R.id.tv_details_goods_phone)
    TextView mTvDetailsGoodsPhone;
    @Bind(R.id.tv_details_add_service_money)
    TextView mTvDetailsAddServiceMoney;
    @Bind(R.id.tv_details_inarch_name)
    TextView mTvDetailsInarchName;
    @Bind(R.id.tv_details_inarch_phone)
    TextView mTvDetailsInarchPhone;
    @Bind(R.id.tv_details_cancel)
    TextView mTvDetailsCancel;
    @Bind(R.id.tv_details_pay)
    TextView mTvDetailsPay;
    @Bind(R.id.tv_details_offline_pay)
    TextView mTvDetailsOfflinePay;
    @Bind(R.id.tv_details_goods_money)
    TextView mTvDetailsGoodsMoney;
    @Bind(R.id.ll_goods_money)
    LinearLayout mLlGoodsMoney;
    @Bind(R.id.tv_goods_exception)
    TextView mTvGoodsException;
    @Bind(R.id.tv_goods_pay)
    TextView mTvGoodsPay;
    @Bind(R.id.tv_details_evaluation)
    TextView mTvDetailsEvaluation;
    @Bind(R.id.ll_goods_paid)
    LinearLayout mLlGoodsPaid;
    @Bind(R.id.ll_details_pay)
    LinearLayout mLlDetailsPay;
    @Bind(R.id.ll_goods_add)
    LinearLayout mLlDetailsAdd;
    @Bind(R.id.tv_details_service_money)
    TextView mTvDetailsServiceMoney;
    @Bind(R.id.tv_goods_no_add)
    TextView mTvGoodsNoAdd;
    @Bind(R.id.tv_goods_add)
    TextView mTvGoodsAdd;
    @Bind(R.id.iv_order_details_pic)
    ImageView mIvOrderDetailsPic;

    private OrderEntity order;
    private String busId;
    private List<String> imageList = new ArrayList<>();
    private OrderDetailsAdapter mOrderDetailsAdapter;
    CommonAdapter<String> commonAdapter;

    private Dialog mCancelDialog;
    private String role = "1";


    public static SendOrdersDetailsFragment newInstance(String busId) {
        SendOrdersDetailsFragment fragment = new SendOrdersDetailsFragment();
        Bundle bundle = new Bundle();
        bundle.putString(UIHelper.BUS_ID, busId);
        fragment.setArguments(bundle);
        return fragment;

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            busId = getArguments().getString(UIHelper.BUS_ID);
        }
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_order_details;
    }

    @Override
    protected void initView(View rootView) {
        super.initView(rootView);
        setTitle(R.string.details_order_title, R.color.white)
                .setTitleBgColor(R.color.generic_view_bg)
                .setImgLeftListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        removeFragment();
                    }
                });


        init();
    }

    public void init() {

        if (AccountModel.getInstance().getRoleType().equals("user")) {
            role = "1";
        } else {
            role = "2";
        }
        mOrderDetailsAdapter = new OrderDetailsAdapter(imageList);
        commonAdapter=new CommonAdapter<String>(getActivity(),imageList,R.layout.item_order_details) {
            @Override
            public void convert(CommonViewHolder holder, String s, final int position) {
                final String url="http://www."+s;
                holder.setGImage(R.id.iv_order_details_pic,url);
                holder.setOnClickListener(R.id.iv_order_details_pic, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        UIHelper.showPicZoom(getActivity(),url);
                    }
                });
            }
        };
        mRvDetailsPic.setAdapter(commonAdapter);
//        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
//        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
//        mRvDetailsPic.setLayoutManager(linearLayoutManager);
//        mRvDetailsPic.setAdapter(mOrderDetailsAdapter);
//        mRvDetailsPic.addOnItemTouchListener(new OnItemClickListener() {
//            @Override
//            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
//
//            }
//
//            @Override
//            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//
//                super.onItemChildClick(adapter, view, position);
//                UIHelper.showPicZoom(getActivity(), imageList.get(position));
//            }
//        });
        getOrderDetails();
    }


    /**
     * (订单类型:'0,未付服务费
     * 1,待接单(服务费付过)
     * 2,已接单(待沟通付款)
     * 3,付过商品/服务费(开始做事)
     * 4,已经购买/取货/送货
     * 5,跑客确认完成(请求用户确认)
     * 6,用户确认(订单完成)
     * 7,评价完成
     * 8,订单取消
     * 9,订单异常 ',)
     *
     * @param info
     */
    private void upOrderDetails(OrderEntity info) {

        if ((info.getOrderStatus() != 4)&&(info.getOrderStatus() != 3)&&(info.getOrderStatus() != 5)) {
            setTvRightBg(R.string.details_order_goods_exception)
                    .setImgRightListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            addFragment(OrderExceptionFragment.newInstance(order));
                        }
                    });
        }
        if (info.getOrderStatus() == 1) {
            mTvDetailsAddServiceMoney.setVisibility(View.VISIBLE);
            mTvDetailsCancel.setVisibility(View.VISIBLE);
            mTvDetailsType.setText(getActivity().getResources().getString(R.string.generic_order_type_one));
        } else if (info.getOrderStatus() == 2) {
            mLlDetailsPay.setVisibility(View.VISIBLE);
            mTvDetailsType.setText(getActivity().getResources().getString(R.string.generic_order_type_two));

        } else if (info.getOrderStatus() == 5) {
            mLlGoodsPaid.setVisibility(View.VISIBLE);
            mLlGoodsMoney.setVisibility(View.VISIBLE);
            mTvDetailsType.setText(getActivity().getResources().getString(R.string.generic_order_type_five));
        } else if (info.getOrderStatus() == 6) {
            mTvDetailsEvaluation.setVisibility(View.VISIBLE);
            mLlGoodsMoney.setVisibility(View.VISIBLE);
            mTvDetailsType.setText(getActivity().getResources().getString(R.string.generic_order_type_six));
        } else if (info.getOrderStatus() == 7) {
            mLlGoodsMoney.setVisibility(View.VISIBLE);
            mTvDetailsType.setText(getActivity().getResources().getString(R.string.generic_order_type_seven));
        } else if (info.getOrderStatus() == 8) {
            mLlGoodsMoney.setVisibility(View.VISIBLE);
            mTvDetailsType.setText(getActivity().getResources().getString(R.string.generic_order_type_eight));
        } else if (info.getOrderStatus() == 9) {
            mLlGoodsMoney.setVisibility(View.VISIBLE);
            mTvDetailsType.setText(getActivity().getResources().getString(R.string.generic_order_type_night));
        }
        if (info.getBusType() == 1) {
            Glide.with(getActivity())
                    .load(R.drawable.iv_details_agecy)
                    .into(mIvOrderDetailsPic);
            if (info.getOrderStatus() == 3) {
                if (info.getOfflinePayGoods().equals("true")) {
                    mTvDetailsType.setText(getActivity().getResources().getString(R.string.details_order_offline_pay));
                } else {
                    mTvDetailsType.setText(getActivity().getResources().getString(R.string.generic_minn_order_type_three));
                }
                mLlGoodsMoney.setVisibility(View.VISIBLE);
            } else if (info.getOrderStatus() == 4) {
                mTvDetailsType.setText(getActivity().getResources().getString(R.string.generic_minn_order_type_four));
                mLlDetailsAdd.setVisibility(View.VISIBLE);
                mLlGoodsMoney.setVisibility(View.VISIBLE);
            }
        } else if (info.getBusType() == 2) {
            Glide.with(getActivity())
                    .load(R.drawable.iv_details_minnetonka)
                    .into(mIvOrderDetailsPic);
            if (info.getOrderStatus() == 3) {
                if (info.getOfflinePayGoods().equals("true")) {
                    mTvDetailsType.setText(getActivity().getResources().getString(R.string.details_order_offline_pay));
                } else {
                    mTvDetailsType.setText(getActivity().getResources().getString(R.string.generic_take_order_type_three));
                }
                mTvDetailsType.setText(getActivity().getResources().getString(R.string.generic_take_order_type_three));
                mLlGoodsMoney.setVisibility(View.VISIBLE);
            } else if (info.getOrderStatus() == 4) {
                mTvDetailsType.setText(getActivity().getResources().getString(R.string.generic_take_order_type_four));
                mLlDetailsAdd.setVisibility(View.VISIBLE);
                mLlGoodsMoney.setVisibility(View.VISIBLE);
            }
        } else if (info.getBusType() == 3) {
            Glide.with(getActivity())
                    .load(R.drawable.iv_details_take)
                    .into(mIvOrderDetailsPic);
            if (info.getOrderStatus() == 3) {
                mLlGoodsMoney.setVisibility(View.VISIBLE);
                if (info.getOfflinePayGoods().equals("true")) {
                    mTvDetailsType.setText(getActivity().getResources().getString(R.string.details_order_offline_pay));
                } else {
                    mTvDetailsType.setText(getActivity().getResources().getString(R.string.generic_agency_order_type_three));
                }
            } else if (info.getOrderStatus() == 4) {
                mLlGoodsMoney.setVisibility(View.VISIBLE);
                mLlDetailsAdd.setVisibility(View.VISIBLE);
                mTvDetailsType.setText(getActivity().getResources().getString(R.string.generic_agency_order_type_four));
            }
        }
        mTvDetailsGoodsName.setText(info.getRemark());
        //imageList = info.getPicPath();
        imageList.addAll(info.getPicPath());
        commonAdapter.refresh(imageList);
//        mOrderDetailsAdapter.setNewData(imageList);
//        mOrderDetailsAdapter.notifyDataSetChanged();
        if (info.getHopeTime() == 0) {
            mTvDetailsTime.setText(getActivity().getString(R.string.generic_order_success_time));
        } else {
            mTvDetailsTime.setText(TimeUtils.milliseconds2String(Long.valueOf(info.getHopeTime()) * 1000, TimeUtils.SUCCESS_MONTH));
        }
        mTvDetailsAddress.setText("指定购物地点" + info.getPostAddr());
        mTvDetailsAddresses.setText(info.getGetAddr());
        mTvDetailsGoodsPhone.setText(info.getGetPhone());
        mTvDetailsServiceMoney.setText("￥" + info.getServiceMoney());
        if (info.getOfflinePayGoods().equals("true") || StringUtils.isEmpty(info.getOfflinePayGoods())) {
            mTvDetailsGoodsMoney.setText(getActivity().getResources().getString(R.string.details_order_offline_pay));

        } else {
            mTvDetailsGoodsMoney.setText(info.getSpendMoney());

        }
        mTvDetailsInarchName.setText(info.getRunName());
        mTvDetailsInarchPhone.setText(info.getRunPhoneNum());
    }

    @OnClick({R.id.tv_details_add_service_money, R.id.tv_details_cancel, R.id.tv_goods_no_add, R.id.tv_goods_add, R.id.tv_details_offline_pay, R.id.tv_details_pay, R.id.tv_goods_pay, R.id.tv_goods_exception, R.id.tv_details_evaluation})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_details_add_service_money:
                getServiceMoney();
                break;
            case R.id.tv_goods_no_add:
                removeFragment();
                break;
            case R.id.tv_goods_add:
                getServiceMoney();
                break;
            case R.id.tv_details_cancel:
                mCancelDialog = new Dialog(getActivity(), R.style.dialog);
                mCancelDialog.setContentView(R.layout.dialog_details_order_out);
                TextView contiune = (TextView) mCancelDialog.findViewById(R.id.tv_dialog_continue);
                TextView out = (TextView) mCancelDialog.findViewById(R.id.tv_dialog_out);
                contiune.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mCancelDialog.dismiss();
                    }
                });
                out.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        cancelOrder();
                        mCancelDialog.dismiss();
                    }
                });
                mCancelDialog.show();
                break;
            case R.id.tv_details_pay:
                addFragment(OrderPayFragment.newInstance(order.getId() + "", order.getServiceMoney()));
                break;
            case R.id.tv_goods_pay:
                completeOrder();
                break;
            case R.id.tv_goods_exception:
                getServiceMoney();
                break;
            case R.id.tv_details_evaluation:
                UIHelper.showDialogEvaluation(getActivity(), order);

                break;
            case R.id.tv_details_offline_pay:
                offLinePay();
                break;
        }
    }

    /**
     * 订单详情
     */
    private void getOrderDetails() {

        addSubscribe(DataManager.getInstance().getUserApi()
                .getOrderDetaile(busId + "", role)
                .compose(RxHelper.<OrderEntity>defaultHandleResult())
                .subscribe(new RxSubscribe<OrderEntity>() {
                    @Override
                    protected void onSucc(OrderEntity orderDetailsInfo) {
                        order = orderDetailsInfo;
                        upOrderDetails(orderDetailsInfo);
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.showToast(msg);
                    }
                }));
    }

    /**
     * 取消订单
     */
    private void cancelOrder() {
        addSubscribe(DataManager.getInstance().getUserApi()
                .cancelOrder(order.getId() + "")
                .compose(RxHelper.<BaseResult>rxSchedulerHelper())
                .subscribe(new RxSubscribe<BaseResult>() {
                    @Override
                    protected void onSucc(BaseResult baseResult) {
                        ToastUtil.showToast(baseResult.msg);
                        getActivity().finish();
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.showToast(msg);
                    }
                }));
    }


    /**
     * 获取服务费
     */
    private void getServiceMoney() {

        addSubscribe(DataManager.getInstance().getUserApi()
                .getServiceMoney()
                .compose(RxHelper.<ServiceMoney>defaultHandleResult())
                .subscribe(new RxSubscribe<ServiceMoney>() {
                    @Override
                    protected void onSucc(ServiceMoney serviceInfo) {
                        UIHelper.showDialogAddServiceMoney(getActivity(), serviceInfo, order.getId() + "");

                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.showToast(msg);
                    }
                }));
    }

    /**
     * 确认订单
     */
    private void completeOrder() {
        addSubscribe(DataManager.getInstance().getUserApi()
                .completeOrder(order.getId() + "")
                .compose(RxHelper.<BaseResult>rxSchedulerHelper())
                .subscribe(new RxSubscribe<BaseResult>() {
                    @Override
                    protected void onSucc(BaseResult baseResult) {
                        getActivity().finish();
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.showToast(msg);
                    }
                }));
    }

    /**
     * 线下支付
     */
    private void offLinePay() {
        addSubscribe(DataManager.getInstance().getUserApi()
                .setOfflinePay(order.getId() + "", "true")
                .compose(RxHelper.<BaseResult>rxSchedulerHelper())
                .subscribe(new RxSubscribe<BaseResult>() {
                    @Override
                    protected void onSucc(BaseResult baseResult) {
                        ToastUtil.showToast(baseResult.msg);
                        mLlDetailsPay.setVisibility(View.GONE);
                        getOrderDetails();
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.showToast(msg);
                    }
                }));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(AddServiceEvent model) {
        if (model.getSuccess().equals("0")) {
            getOrderDetails();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EavluationEvent type) {
        if (type.getType().equals("0")) {
            getActivity().finish();
        }
    }
}
